"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

import graphene
from graphql import GraphQLError
from django.apps import apps
from django.utils.translation import gettext_lazy as _

from main.models import SiriusoBazaAbstrakta, Uzanto


class Statistiko(graphene.ObjectType):
    modelo = graphene.String()
    kondichoj = graphene.String()
    komenco_periodo = graphene.DateTime()
    fino_periodo = graphene.DateTime()
    tuta = graphene.Int(required=True)
    gajno = graphene.Int()
    procento = graphene.Float()

    def resolve_tuta(self, info):
        try:
            app_label, model_name = str(self.modelo).split('.')
            model = apps.get_model(app_label, model_name)
        except:
            raise GraphQLError(_('Модель не найдена'))

        conditions = {}
        conditions2 = {}
        date_field = 'krea_dato'

        if self.kondichoj:
            kond_list = self.kondichoj.split(';')

            for kond in kond_list:
                field, val = kond.split(':')
                val = val.split(',') if val.find(',') > -1 else val
                conditions[field] = val

        if issubclass(model, SiriusoBazaAbstrakta):
            conditions['forigo'] = False
        elif issubclass(model, Uzanto):
            conditions.update({'is_active': True, 'konfirmita': True})

        conditions2.update(conditions)

        if self.komenco_periodo:
            conditions2['{}__gte'.format(date_field)] = self.komenco_periodo
        if self.fino_periodo:
            conditions2['{}__lte'.format(date_field)] = self.fino_periodo
            conditions['{}__lte'.format(date_field)] = self.fino_periodo

        query = model.objects.filter(**conditions)
        tuta = query.count()

        query2 = query.filter(**conditions2)
        self.gajno = query2.count()

        try:
            self.procento = 100 * self.gajno / (tuta - self.gajno)
        except ZeroDivisionError:
            self.procento = 100

        return tuta


class Queries(graphene.ObjectType):
    """
    Возвращает статистику прироста записей определенной модели
    """
    statistiko = graphene.Field(Statistiko, modelo=graphene.String(required=True), komenco=graphene.DateTime(),
                                kondichoj=graphene.String(), fino=graphene.DateTime())

    def resolve_statistiko(self, info, modelo,**kwargs):
        if not info.context.user.is_authenticated:
            raise GraphQLError(_('Необходима авторизация'))
        #elif not info.context.user.is_admin:
        #    raise GraphQLError(_('Недостаточно прав для получения информации'))
        return Statistiko(modelo=modelo, kondichoj=kwargs.get("kondichoj"),komenco_periodo=kwargs.get('komenco'),
                          fino_periodo=kwargs.get('fino'))
